<template>
  <div class="login">
    <el-form class="logins" ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
      <el-form-item prop="account">
        <el-input style="display: none;"> </el-input>
        <el-input v-model="form.account" placeholder="请输入用户名">
    <span slot="prepend">
        <i class="el-icon-user"></i>
      </span>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" style="display: none;"> </el-input>
        <el-input type="password" v-model="form.password" placeholder="请输入密码">
      <span slot="prepend">
        <i class="el-icon-lock"></i>
      </span>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSubmit" type="primary">登入</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import md5 from 'js-md5';//md5加密
import {login} from '../../api/ajax'
import { mapActions } from 'vuex'
export default {
  name: 'index',
  props: {
    accountRules: {
      type: Array,
      default: () => {
        return [
          {required: true, message: '账号不能为空', trigger: 'blur'}
        ]
      }
    },
    passwordRules: {
      type: Array,
      default: () => {
        return [
          {required: true, message: '密码不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  data () {
    return {
      form: {
        account: '',
        password: ''
      }
    }
  },
  computed: {
    rules () {
      return {
        account: this.accountRules,
        password: this.passwordRules
      }
    }
  },
  methods: {
    ...mapActions([
      'updateUserInfo'
    ]),
    handleSubmit () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          login({
            ...this.form,
          }).then(res => {
            console.log(res.data)
            if (res.data.code === 1) {
              this.updateUserInfo(res.data.data)
              this.$message.success('登录成功')
              this.$router.push({
                name: 'index'
              })
              this.$store.state.access_token = res.data.data.access_token;
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
  .login{
    margin: 200px auto;
    width: 400px;
    button{
      width: 100%;
    }
  }
</style>
